<template>
  <div id="cesium">
    <div id="map"></div>
    <div class="box">
      <el-switch
        v-model="SProvider"
        inactive-text="切换底图"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="CProvider"
      >
      </el-switch>

      <el-switch
        v-model="Sgeojson"
        inactive-text="边界(GeoJson)"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Cgeojson"
      >
      </el-switch>

      <el-switch
        v-model="Sdimensional"
        inactive-text="2/3D"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Cdimensional"
      >
      </el-switch>

      <el-switch
        v-model="Sgrid"
        inactive-text="网格"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Cgrid"
      >
      </el-switch>

      <el-switch
        v-model="Scontour"
        inactive-text="等高线"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Ccontour"
      >
      </el-switch>

      <el-switch
        v-model="Spoint"
        inactive-text="点"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Cpoint"
      >
      </el-switch>

      <el-switch
        v-model="Spolyline"
        inactive-text="线段"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Cpolyline"
      >
      </el-switch>

      <el-switch
        v-model="Slabel"
        inactive-text="标签"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Clabel"
      >
      </el-switch>

      <el-switch
        v-model="Sbillboard"
        inactive-text="图标"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Cbillboard"
      >
      </el-switch>

      <el-switch
        v-model="Simage"
        inactive-text="图片"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Cimage"
      >
      </el-switch>

      <el-switch
        v-model="Scircular"
        inactive-text="圆形"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Ccircular"
      >
      </el-switch>

      <el-switch
        v-model="Srectangle"
        inactive-text="矩形"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Crectangle"
      >
      </el-switch>

      <el-switch
        v-model="Spolygon"
        inactive-text="多边形"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Cpolygon"
      >
      </el-switch>

      <el-switch
        v-model="Swall"
        inactive-text="墙"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Cwall"
      >
      </el-switch>

      <el-switch
        v-model="Splane"
        inactive-text="平面"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Cplane"
      >
      </el-switch>

      <el-switch
        v-model="Ssphere"
        inactive-text="球体"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Csphere"
      >
      </el-switch>

      <el-switch
        v-model="Scylinder"
        inactive-text="圆柱体"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Ccylinder"
      >
      </el-switch>

      <el-switch
        v-model="Srectangular"
        inactive-text="矩形立方体"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Crectangular"
      >
      </el-switch>

      <el-switch
        v-model="Spolygonal"
        inactive-text="多边形立方体"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Cpolygonal"
      >
      </el-switch>

      <el-switch
        v-model="Swind"
        inactive-text="风场"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Cwind"
      >
      </el-switch>

      <el-switch
        v-model="SpointPrimitiveCollection"
        inactive-text="点集合"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="CpointPrimitiveCollection"
      >
      </el-switch>

      <el-switch
        v-model="SlabelCollection"
        inactive-text="标签集合"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="ClabelCollection"
      >
      </el-switch>

      <el-switch
        v-model="SdataSources"
        inactive-text="站点"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="CdataSources"
      >
      </el-switch>

      <el-switch
        v-model="Senable"
        inactive-text="模型"
        active-color="#6cf"
        inactive-color="rgb(0,0,0)"
        @change="Cenable"
      >
      </el-switch>
    </div>
    <el-card class="box-card">
      <el-button
        v-for="(item, index) in btns"
        :key="index"
        class="btn"
        :style="item == 'cesium' ? 'display:none' : ''"
        @click="btn(item)"
        >{{ item }}</el-button
      >
    </el-card>
  </div>
</template>

<script>
import { mapState } from "vuex";
import axios from "axios";
import ColorTable from "@/utils/wind/colorTable.js";
import Wind3D from "@/utils/wind/wind3D.js";
import NetCDFReader from "@/utils/netcdfjs/src/index";

export default {
  computed: {
    ...mapState({
      btns: (state) => state.vuex.btns,
    }),
  },
  data() {
    return {
      map: null,
      // mapUrl1: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
      mapUrl1:
        "http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity_Mobile/MapServer/tile/{z}/{y}/{x}",
      mapUrl2:
        "http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}",
      provider1: null,
      provider2: null,
      providerAlpha: 1,
      SProvider: false,

      Sgeojson: false,
      china: null,
      jiangsu: null,

      Sdimensional: false,

      Sgrid: false,
      grid: null,

      Scontour: false,

      Spoint: false,
      point: null,

      Spolyline: false,
      polyline: null,

      Slabel: false,
      label: null,

      Sbillboard: false,
      billboard: null,

      Simage: false,
      image: null,

      Scircular: false,
      circular: null,

      Srectangle: false,
      rectangle: null,

      Spolygon: false,
      polygon: [],

      Swall: false,
      wall: null,

      Splane: false,
      plane: [],

      Ssphere: false,
      sphere: null,

      Scylinder: false,
      cylinder: null,

      Srectangular: false,
      rectangular: null,

      Spolygonal: false,
      polygonal: [],

      nc: null,
      Swind: false,
      wind: null,

      SpointPrimitiveCollection: false,
      pointPrimitiveCollection: null,

      SlabelCollection: false,
      labelCollection: null,

      SdataSources: false,
      dataSources: null,
      dataSourcesImgs: [],

      Senable: false,
      enable: true,
      gltf: null,
    };
  },
  created() {
    this.loadNetCDF();
  },
  mounted() {
    this.initmap();
  },
  methods: {
    initmap() {
      Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJlYTI5MzE4Ny05ZWIwLTQ3Y2EtYWM4OS1lZmNmMDI3ZDZiYjIiLCJpZCI6MTEzMjczLCJpYXQiOjE2NjczMjQyMTl9._Ac_s5R6-FsmKz-6dcTvjQXHhwzPuvCQEXBPB9cKH7Y";
      this.map = new Cesium.Viewer("map", {
        animation: false, //隐藏掉时钟
        timeline: false, //隐藏时间轴
        fullscreenButton: false, //隐藏全屏按钮
        geocoder: false, //隐藏搜索按钮
        homeButton: false, //隐藏home按钮
        navigationHelpButton: false, //隐藏帮助按钮
        creditContainer: document.createElement("div"), //隐藏logo
        sceneModePicker: false, //隐藏切换二三维按钮
        baseLayerPicker: false, //隐藏切换底图按钮
        imageryProvider: false, //底图
        terrainProvider: Cesium.createWorldTerrain({
          requestVertexNormals: true, //光
          requestWaterMask: true, //水
        }), //地形
      });
      this.CProvider(this.SProvider);
      this.map.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(118.8, 32, 10000000),
        duration: 1,
      });
    },
    //切换底图
    CProvider(val) {
      if (val) {
        let provider = new Cesium.UrlTemplateImageryProvider({
          url: this.mapUrl2,
        });
        this.provider2 = this.map.imageryLayers.addImageryProvider(provider, 1);
        this.provider2.alpha = this.providerAlpha;
        if (this.provider1) {
          this.map.imageryLayers.remove(this.provider1);
          this.provider1 = null;
        }
      } else {
        let provider = new Cesium.UrlTemplateImageryProvider({
          url: this.mapUrl1,
        });
        this.provider1 = this.map.imageryLayers.addImageryProvider(provider, 1);
        this.provider1.alpha = this.providerAlpha;
        if (this.provider2) {
          this.map.imageryLayers.remove(this.provider2);
          this.provider2 = null;
        }
      }
    },
    //GeoJson
    Cgeojson(val) {
      if (val) {
        let china = Cesium.GeoJsonDataSource.load(
          "./static/chinaBoundary.geojson",
          {
            stroke: Cesium.Color.RED,
            fill: Cesium.Color.TRANSPARENT,
          }
        );
        let jiangsu = Cesium.GeoJsonDataSource.load(
          "./static/jiangsuBoundary.geojson",
          {
            stroke: Cesium.Color.fromCssColorString("#6cf"),
            fill: Cesium.Color.TRANSPARENT,
          }
        );
        china.then((res) => {
          this.china = res;
          this.map.dataSources.add(res);
        });
        jiangsu.then((res) => {
          this.jiangsu = res;
          this.map.dataSources.add(res);
        });
      } else {
        if (this.china) {
          this.map.dataSources.remove(this.china);
          this.china = null;
        }
        if (this.jiangsu) {
          this.map.dataSources.remove(this.jiangsu);
          this.jiangsu = null;
        }
      }
    },
    //2/3D
    Cdimensional(val) {
      if (val) {
        this.map.scene.morphTo2D();
      } else {
        this.map.scene.morphTo3D();
      }
    },
    //网格
    Cgrid(val) {
      if (val) {
        let grid = new Cesium.GridImageryProvider({
          cells: 4, //网格单元的数量
          color: Cesium.Color.fromCssColorString("#6cf"), //网格线的颜色
          glowColor: Cesium.Color.fromCssColorString("#6cf"), //网格线发光的颜色
          glowWidth: 1, //线条宽度
          backgroundColor: Cesium.Color.TRANSPARENT, //背景颜色
        });
        this.grid = this.map.imageryLayers.addImageryProvider(grid, 2);
      } else {
        if (this.grid) {
          this.map.imageryLayers.remove(this.grid);
          this.grid = null;
        }
      }
    },
    //等高线
    Ccontour(val) {
      if (val) {
        // 使用等高线材质
        let material = Cesium.Material.fromType("ElevationContour");
        let contourUniforms = material.uniforms;
        // 线宽px
        contourUniforms.width = 1;
        // 高度间隔m
        contourUniforms.spacing = 1000;
        //颜色
        contourUniforms.color = Cesium.Color.fromCssColorString("#6cf");
        // 设置材质
        this.map.scene.globe.material = material;
      } else {
        this.map.scene.globe.material =
          this.map.scene.globe.material &&
          this.map.scene.globe.material.destroy();
      }
    },
    //点
    Cpoint(val) {
      if (val) {
        this.point = this.map.entities.add({
          position: Cesium.Cartesian3.fromDegrees(118.8, 32),
          point: {
            pixelSize: 14,
            color: Cesium.Color.fromCssColorString("#6cf"),
            outlineColor: Cesium.Color.BLACK,
            outlineWidth: 1,
          },
        });
      } else {
        if (this.point) {
          this.map.entities.remove(this.point);
          this.point = null;
        }
      }
    },
    //线段
    Cpolyline(val) {
      if (val) {
        let polyline1 = this.map.entities.add({
          polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray([110, 30, 120, 40]),
            width: 4,
            material: Cesium.Color.fromCssColorString("#000"),
            clampToGround: true, //固定在地面上
          },
        });
        let polyline2 = this.map.entities.add({
          polyline: {
            positions: Cesium.Cartesian3.fromDegreesArrayHeights([
              110, 30, 666666, 120, 40, 888888,
            ]),
            width: 4,
            material: new Cesium.PolylineOutlineMaterialProperty({
              color: Cesium.Color.fromCssColorString("#6cf"),
              outlineWidth: 2,
              outlineColor: Cesium.Color.BLACK,
            }),
          },
        });
        this.polyline = [polyline1, polyline2];
      } else {
        if (this.polyline.length) {
          this.polyline.forEach((item) => {
            this.map.entities.remove(item);
          });
          this.polyline = [];
        }
      }
    },
    //标签
    Clabel(val) {
      if (val) {
        this.label = this.map.entities.add({
          position: Cesium.Cartesian3.fromDegrees(118.8, 32),
          label: {
            text: "鸡你太美",
            font: "44px SimSun",
            fillColor: Cesium.Color.fromCssColorString("#6cf"),
            outlineWidth: 1,
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          },
        });
      } else {
        if (this.label) {
          this.map.entities.remove(this.label);
          this.label = null;
        }
      }
    },
    //图标
    Cbillboard(val) {
      if (val) {
        this.billboard = this.map.entities.add({
          position: Cesium.Cartesian3.fromDegrees(118.8, 32),
          billboard: {
            image: require("@/assets/logo.png"),
            scale: 0.1,
          },
        });
      } else {
        if (this.billboard) {
          this.map.entities.remove(this.billboard);
          this.billboard = null;
        }
      }
    },
    //图片
    Cimage(val) {
      if (val) {
        this.image = this.map.entities.add({
          rectangle: {
            coordinates: Cesium.Rectangle.fromDegrees(115, 30, 121, 35),
            height: 0,
            outline: true,
            outlineColor: Cesium.Color.fromCssColorString("#6cf"),
            material: new Cesium.ImageMaterialProperty({
              image: require("@/assets/logo.png"),
              transparent: true,
            }),
          },
        });
      } else {
        if (this.image) {
          this.map.entities.remove(this.image);
          this.image = null;
        }
      }
    },
    //圆形
    Ccircular(val) {
      if (val) {
        this.circular = this.map.entities.add({
          position: Cesium.Cartesian3.fromDegrees(118.8, 32),
          ellipse: {
            semiMinorAxis: 666666,
            semiMajorAxis: 666666,
            height: 111111,
            outline: true,
            outlineColor: Cesium.Color.fromCssColorString("#000"),
            material: Cesium.Color.fromCssColorString("#6cf").withAlpha(0.4),
          },
        });
      } else {
        if (this.circular) {
          this.map.entities.remove(this.circular);
          this.circular = null;
        }
      }
    },
    //矩形
    Crectangle(val) {
      if (val) {
        this.rectangle = this.map.entities.add({
          rectangle: {
            coordinates: Cesium.Rectangle.fromDegrees(115, 30, 121, 35),
            height: 222222,
            outline: true,
            outlineColor: Cesium.Color.fromCssColorString("#000"),
            material: Cesium.Color.fromCssColorString("#6cf").withAlpha(0.4),
          },
        });
      } else {
        if (this.rectangle) {
          this.map.entities.remove(this.rectangle);
          this.rectangle = null;
        }
      }
    },
    //多边形
    Cpolygon(val) {
      if (val) {
        let polygon1 = this.map.entities.add({
          polygon: {
            hierarchy: new Cesium.PolygonHierarchy(
              Cesium.Cartesian3.fromDegreesArray([
                120, 30, 130, 40, 110, 40, 100, 30,
              ]) // [经度，纬度，经度，纬度...]
            ),
            height: 333333,
            outline: true,
            outlineColor: Cesium.Color.fromCssColorString("#000"),
            material: Cesium.Color.fromCssColorString("#6cf").withAlpha(0.4),
          },
        });
        let polygon2 = this.map.entities.add({
          polygon: {
            hierarchy: Cesium.Cartesian3.fromDegreesArrayHeights([
              120, 30, 100000, 130, 60, 500000, 140, 20, 2000000,
            ]), //顶点高度不同
            outline: true,
            perPositionHeight: true, //是否使用每个位置的高度
            outlineColor: Cesium.Color.fromCssColorString("#000"),
            material: Cesium.Color.fromCssColorString("#6cf").withAlpha(0.4),
          },
        });
        this.polygon = [polygon1, polygon2];
      } else {
        if (this.polygon.length) {
          this.polygon.forEach((item) => {
            this.map.entities.remove(item);
          });
          this.polygon = [];
        }
      }
    },
    //墙
    Cwall(val) {
      if (val) {
        this.wall = this.map.entities.add({
          wall: {
            positions: Cesium.Cartesian3.fromDegreesArray([
              120, 50, 110, 40, 90, 50,
            ]), //墙顶
            maximumHeights: [500000, 1000000, 800000], //墙顶的高度
            minimumHeights: [100000, 200000, 700000], //墙底的高度
            outline: true,
            outlineColor: Cesium.Color.fromCssColorString("#000"),
            material: Cesium.Color.fromCssColorString("#6cf").withAlpha(0.4),
          },
        });
      } else {
        if (this.wall) {
          this.map.entities.remove(this.wall);
          this.wall = null;
        }
      }
    },
    //平面
    Cplane(val) {
      if (val) {
        let plane1 = this.map.entities.add({
          position: Cesium.Cartesian3.fromDegrees(100, 50, 1111111),
          plane: {
            plane: new Cesium.Plane(Cesium.Cartesian3.UNIT_X, 0.0), //法线
            dimensions: new Cesium.Cartesian2(2000000, 1500000), //宽高
            material: Cesium.Color.fromCssColorString("#6cf").withAlpha(0.4),
          },
        });
        let plane2 = this.map.entities.add({
          position: Cesium.Cartesian3.fromDegrees(100, 50, 1111111),
          plane: {
            plane: new Cesium.Plane(Cesium.Cartesian3.UNIT_Y, 0.0),
            dimensions: new Cesium.Cartesian2(2000000, 1500000),
            material: Cesium.Color.RED.withAlpha(0.4),
          },
        });
        let plane3 = this.map.entities.add({
          position: Cesium.Cartesian3.fromDegrees(100, 50, 1111111),
          plane: {
            plane: new Cesium.Plane(Cesium.Cartesian3.UNIT_Z, 0.0),
            dimensions: new Cesium.Cartesian2(2000000, 2000000),
            fill: false,
            outline: true,
            outlineColor: Cesium.Color.YELLOW,
          },
        });
        this.plane = [plane1, plane2, plane3];
      } else {
        if (this.plane.length) {
          this.plane.forEach((item) => {
            this.map.entities.remove(item);
          });
          this.plane = [];
        }
      }
    },
    //球体
    Csphere(val) {
      if (val) {
        this.sphere = this.map.entities.add({
          position: Cesium.Cartesian3.fromDegrees(85, 40, 888888),
          ellipsoid: {
            radii: new Cesium.Cartesian3(666666, 666666, 666666),
            outline: true,
            outlineColor: Cesium.Color.BLACK,
            material: Cesium.Color.fromCssColorString("#6cf").withAlpha(0.4),
          },
        });
      } else {
        if (this.sphere) {
          this.map.entities.remove(this.sphere);
          this.sphere = null;
        }
      }
    },
    //圆柱体
    Ccylinder(val) {
      if (val) {
        this.cylinder = this.map.entities.add({
          position: Cesium.Cartesian3.fromDegrees(150, 50),
          ellipse: {
            semiMinorAxis: 100000,
            semiMajorAxis: 100000,
            height: 400000,
            extrudedHeight: 100000, //凸出面相对于地球表面的高度
            outline: true,
            outlineColor: Cesium.Color.BLACK,
            material: Cesium.Color.fromCssColorString("#6cf").withAlpha(0.4),
          },
        });
      } else {
        if (this.cylinder) {
          this.map.entities.remove(this.cylinder);
          this.cylinder = null;
        }
      }
    },
    //矩形立方体
    Crectangular(val) {
      if (val) {
        this.rectangular = this.map.entities.add({
          rectangle: {
            coordinates: Cesium.Rectangle.fromDegrees(160, 50, 170, 55),
            height: 400000,
            extrudedHeight: 100000,
            outline: true,
            outlineColor: Cesium.Color.BLACK,
            material: Cesium.Color.fromCssColorString("#6cf").withAlpha(0.4),
          },
        });
      } else {
        if (this.rectangular) {
          this.map.entities.remove(this.rectangular);
          this.rectangular = null;
        }
      }
    },
    //多边形立方体
    Cpolygonal(val) {
      if (val) {
        let polygonal1 = this.map.entities.add({
          polygon: {
            hierarchy: new Cesium.PolygonHierarchy(
              Cesium.Cartesian3.fromDegreesArray([80, 20, 90, 25, 85, 30])
            ),
            height: 400000,
            extrudedHeight: 100000,
            outline: true,
            outlineColor: Cesium.Color.BLACK,
            material: Cesium.Color.fromCssColorString("#6cf").withAlpha(0.4),
          },
        });
        let polygonal2 = this.map.entities.add({
          polygon: {
            hierarchy: Cesium.Cartesian3.fromDegreesArrayHeights([
              70, 10, 200000, 80, 15, 500000, 75, 20, 1000000,
            ]), //顶点高度不同
            extrudedHeight: 100000,
            perPositionHeight: true,
            outline: true,
            outlineColor: Cesium.Color.BLACK,
            material: Cesium.Color.fromCssColorString("#6cf").withAlpha(0.4),
          },
        });
        this.polygonal = [polygonal1, polygonal2];
      } else {
        if (this.polygonal.length) {
          this.polygonal.forEach((item) => {
            this.map.entities.remove(item);
          });
          this.polygonal = [];
        }
      }
    },
    //风场
    Cwind(val) {
      if (val) {
        this.wind = new Wind3D(this.map, this.nc, {
          particlesTextureSize: 128,
          maxParticles: 128 * 128,
          particleHeight: 100.0,
          fadeOpacity: 0.999,
          dropRate: 0.003,
          dropRateBump: 0.01,
          speedFactor: 4.0,
          lineWidth: 2.0,
        });
      } else {
        if (this.wind) {
          this.wind.destroy();
          this.wind = null;
        }
      }
    },
    //nc
    loadNetCDF() {
      axios({
        method: "get",
        responseType: "arraybuffer",
        url: "./static/demo.nc",
      }).then((res) => {
        var loadColorTable = function (type) {
          const json = ColorTable;
          const colorNum = json.ncolors;
          let colorTable;
          colorTable = json.windColorTable;
          const colorsArray = new Float32Array(3 * colorNum);
          for (let i = 0; i < colorNum; i++) {
            colorsArray[3 * i] = colorTable[3 * i];
            colorsArray[3 * i + 1] = colorTable[3 * i + 1];
            colorsArray[3 * i + 2] = colorTable[3 * i + 2];
          }
          const result = {};
          result.colorNum = colorNum;
          result.array = colorsArray;
          return result;
        };

        var arrayToMap = function (array) {
          return array.reduce(function (map, object) {
            map[object.name] = object;
            return map;
          }, {});
        };

        var NetCDF = new NetCDFReader(res.data);
        var data = {};

        var dimensions = arrayToMap(NetCDF.dimensions);
        data.dimensions = {};
        data.dimensions.lon = dimensions["lon"].size;
        data.dimensions.lat = dimensions["lat"].size;
        data.dimensions.lev = dimensions["lev"].size;

        var variables = arrayToMap(NetCDF.variables);
        var uAttributes = arrayToMap(variables["U"].attributes);
        var vAttributes = arrayToMap(variables["V"].attributes);

        data.lon = {};
        data.lon.array = new Float32Array(NetCDF.getDataVariable("lon").flat());
        data.lon.min = Math.min(...data.lon.array);
        data.lon.max = Math.max(...data.lon.array);

        data.lat = {};
        data.lat.array = new Float32Array(NetCDF.getDataVariable("lat").flat());
        data.lat.min = Math.min(...data.lat.array);
        data.lat.max = Math.max(...data.lat.array);

        data.lev = {};
        data.lev.array = new Float32Array(NetCDF.getDataVariable("lev").flat());
        data.lev.min = Math.min(...data.lev.array);
        data.lev.max = Math.max(...data.lev.array);

        data.U = {};
        data.U.array = new Float32Array(NetCDF.getDataVariable("U").flat());
        data.U.min = uAttributes["min"].value;
        data.U.max = uAttributes["max"].value;

        data.V = {};
        data.V.array = new Float32Array(NetCDF.getDataVariable("V").flat());
        data.V.min = vAttributes["min"].value;
        data.V.max = vAttributes["max"].value;

        data.colorTable = loadColorTable();
        this.nc = data;
      });
    },
    //点集合
    CpointPrimitiveCollection(val) {
      if (val) {
        this.pointPrimitiveCollection = this.map.scene.primitives.add(
          new Cesium.PointPrimitiveCollection()
        );
        let arr = [];
        while (arr.length < 20000) {
          let obj = {
            lon: null,
            lat: null,
            height: null,
            color: null,
          };
          obj.lon = (Math.random() * 360 - 180).toFixed(2);
          obj.lat = (Math.random() * 180 - 90).toFixed(2);
          obj.height = (Math.random() * 10000000).toFixed(2);
          obj.color = `rgb(${Math.round(Math.random() * 255)},${Math.round(
            Math.random() * 255
          )},${Math.round(Math.random() * 255)})`;
          arr.push(obj);
        }
        arr.forEach((item) => {
          this.pointPrimitiveCollection.add({
            position: new Cesium.Cartesian3.fromDegrees(
              item.lon,
              item.lat,
              item.height
            ),
            color: Cesium.Color.fromCssColorString(item.color),
          });
        });
      } else {
        this.map.scene.primitives.remove(this.pointPrimitiveCollection);
        this.pointPrimitiveCollection = null;
      }
    },
    //标签集合
    ClabelCollection(val) {
      if (val) {
        this.labelCollection = this.map.scene.primitives.add(
          new Cesium.LabelCollection()
        );
        let arr = [];
        while (arr.length < 100) {
          let obj = {};
          obj.lon = (Math.random() * 360 - 180).toFixed(2);
          obj.lat = (Math.random() * 180 - 90).toFixed(2);
          obj.height = (Math.random() * 10000000).toFixed(2);
          arr.push(obj);
        }
        arr.forEach((item) => {
          this.labelCollection.add({
            position: new Cesium.Cartesian3.fromDegrees(
              item.lon,
              item.lat,
              item.height
            ),
            text: "鸡你太美",
            font: "14px",
            fillColor: Cesium.Color.fromCssColorString("#6cf"),
          });
        });
      } else {
        this.map.scene.primitives.remove(this.labelCollection);
        this.labelCollection = null;
      }
    },
    //站点
    CdataSources(val) {
      if (val) {
        this.dataSources = new Cesium.CustomDataSource("billboard");
        this.dataSources.show = false;
        this.map.dataSources.add(this.dataSources);
        let arr = [];
        while (arr.length < 1000) {
          let obj = {};
          obj.lon = (Math.random() * 360 - 180).toFixed(2);
          obj.lat = (Math.random() * 180 - 90).toFixed(2);
          obj.rotate = Math.random() * 2;
          arr.push(obj);
        }
        let promiseArr = [];
        arr.forEach((item, index) => {
          let canvas = document.createElement("canvas");
          canvas.width = 100;
          canvas.height = 100;
          let ctx = canvas.getContext("2d");
          ctx.beginPath();
          ctx.fillStyle = "#000";
          ctx.arc(50, 50, 2, 0, 2 * Math.PI);
          ctx.fill();
          ctx.font = "16px Microsoft YaHei";
          ctx.fillText("北", 42, 16);
          ctx.fillText("东", 84, 54);
          ctx.fillText("南", 42, 94);
          ctx.fillText("西", 0, 54);
          let img = new Image();
          img.src = require("@/assets/wind.png");
          let promise = new Promise((resolve, reject) => {
            img.onload = () => {
              ctx.translate(50, 50);
              ctx.rotate(item.rotate * Math.PI);
              ctx.drawImage(img, -1, 0, 13, -23);
              ctx.closePath();
              ctx.stroke();
              let image = new Image();
              image.src = canvas.toDataURL("image/png");
              this.dataSources.entities.add({
                id: index,
                position: Cesium.Cartesian3.fromDegrees(item.lon, item.lat),
                billboard: {
                  image: image,
                  scale: 1,
                },
              });
              this.dataSourcesImgs.push(image);
              resolve();
            };
          });
          promiseArr.push(promise);
        });
        Promise.all(promiseArr).then((res) => {
          this.dataSources.show = true;//是否显示实体
          this.dataSources.clustering.enabled = true;//是否启用聚合
          this.dataSources.clustering.clusterLabels = true;//是否对实体的标签进行聚合
          this.dataSources.clustering.clusterPoints = true;//是否对实体的点进行聚合
          this.dataSources.clustering.pixelRange = 70; //小于这个距离就会被聚合
          this.dataSources.clustering.minimumClusterSize = 2; //每个聚合点的最小聚合个数
          this.dataSources.clustering.clusterEvent.addEventListener(
            (clusteredEntities, cluster) => {
              cluster.label.show = false;
              cluster.billboard.show = true;
              cluster.billboard.image =
                this.dataSourcesImgs[clusteredEntities[0].id];
            }
          );
        });
      } else {
        if (this.dataSources) {
          this.map.dataSources.remove(this.dataSources);
          this.dataSources = null;
          this.dataSourcesImgs = [];
        }
      }
    },
    //模型
    Cenable(val) {
      if (val) {
        this.map.scene.screenSpaceCameraController.enableCollisionDetection = false; //地形碰撞
        this.map.scene.globe.translucency.enabled = true; //全球半透明
        this.map.scene.globe.translucency.frontFaceAlpha = 0; //正面半透明
        this.map.scene.globe.translucency.backFaceAlpha = 0; //背面半透明
        this.map.scene.globe.translucency.rectangle =
          Cesium.Rectangle.fromDegrees(-180, 60, 180, 90); //指定区域半透明
        this.map.scene.globe.showGroundAtmosphere = false; //地面大气层
        this.map.scene.globe.baseColor = Cesium.Color.TRANSPARENT; //基色
        this.map.scene.globe.undergroundColor = undefined; //地下颜色
        this.map.scene.skyAtmosphere.show = false; //天空大气层
        this.providerAlpha = 0.4;
        if (this.provider1) this.provider1.alpha = this.providerAlpha;
        if (this.provider2) this.provider2.alpha = this.providerAlpha;
        this.gltf = this.map.entities.add({
          position: new Cesium.Cartesian3.fromDegrees(0, 90, -2000000),
          model: {
            uri: "./static/cat/scene.gltf",
            scale: 500000,
          },
        });
      } else {
        this.map.scene.screenSpaceCameraController.enableCollisionDetection = true;
        this.map.scene.globe.translucency.enabled = false; //全球半透明
        this.map.scene.globe.translucency.frontFaceAlpha = 1; //正面半透明
        this.map.scene.globe.translucency.backFaceAlpha = 1; //背面半透明
        this.map.scene.globe.showGroundAtmosphere = true; //地面大气层
        this.map.scene.globe.baseColor = new Cesium.Color(0, 0, 0.5, 1); //基色
        this.map.scene.globe.undergroundColor = Cesium.Color.BLACK; //地下颜色
        this.map.scene.skyAtmosphere.show = true; //天空大气层
        this.providerAlpha = 1;
        if (this.provider1) this.provider1.alpha = this.providerAlpha;
        if (this.provider2) this.provider2.alpha = this.providerAlpha;
        if (this.gltf) {
          this.map.entities.remove(this.gltf);
          this.gltf = null;
        }
      }
    },

    btn(val) {
      this.$router.push(`/${val}`);
    },
  },
};
</script>

<style lang="scss" scoped>
#cesium {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;

  #map {
    width: 100%;
    height: 100%;
  }

  .box {
    position: absolute;
    left: 0;
    top: 0;
    width: 150px;
    padding: 0 10px;
    background-color: rgba($color: #000000, $alpha: 0.6);
    z-index: 1000;

    :deep(.el-switch) {
      display: block;
      margin: 5px 0;
    }
    :deep(.el-switch__label),
    :deep(.is-active) {
      color: #fff !important;
    }
  }

  .box-card {
    position: absolute;
    right: 10px;
    bottom: 10px;
    width: 140px;
    height: 440px;
    background-color: rgba($color: #000000, $alpha: 0.6);
    z-index: 1000;
    :deep(.el-card__body) {
      text-align: center;
    }
    .btn {
      width: 100px;
      margin: 0 0 5px;
      background-color: transparent;
      color: #fff;
      &:hover {
        background-color: rgba($color: #000, $alpha: 0.6);
      }
    }
  }
}
</style>